package com.dhecp.core.utils.qywx;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dhecp.common.config.Global;
import com.dhecp.common.utils.CacheUtils;
import com.dhecp.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;

/**
 * @ClassName 企业微信工具类
 * @Description TODO
 * @Author alula
 * @Date 2022-02-24 15:29
 */
public class WeChatUtils {
    private static final Logger logger = LoggerFactory.getLogger(WeChatUtils.class);

    // 企业微信APPID
    public static String APPID = Global.getConfig("wx.corpid");
    // 企业微信H5应用ID：AGENTID
    public static String AGENTID = Global.getConfig("wx.agentid");
    // 企业微信H5应用SECERT：SECERT
    public static String H5SECERT = Global.getConfig("wx.corpsecret");
    // 企业微信通讯录应用：TXLSECERT
    public static String TXLSECERT = Global.getConfig("wx.txlsecret");
    // 企业微信打卡应用：DKSECERT
    public static String DKSECERT = Global.getConfig("wx.dksecret");
    //企业微信H5应用缓存Key
    public static String H5CACHEKEY = "H5ApplyCache";
    //企业微信通讯录应用缓存Key
    public static String TXLCACHEKEY = "TxlApplyCache";
    //企业微信打卡应用缓存Key
    public static String DKCACHEKEY = "DkApplyCache";

    /**
     * 企业微信企业ID
     * @return
     */
    public static  String getCorpId(){
        return APPID;
    }

    /**
     * 获取企业微信H5应用ID
     * @return
     */
    public static String getAgentId(){
        return AGENTID;
    }

    /**
     * 获到微信token
     * @param appId
     * @param appSecret
     * @param cacheKey 应用KEY，主要用于缓存不同应用的token
     * @return
     */
    public static String getToken(String appId , String appSecret, String cacheKey) {
        String token = "";
        String wxTokenExpiresKey = "WxTokenExpires_" +cacheKey;
        String wxTokenKey = "WxToken_"+cacheKey;
        if(CacheUtils.get(wxTokenExpiresKey) == null || CacheUtils.get(wxTokenExpiresKey).equals("") || new Date().after((Date) CacheUtils.get(wxTokenExpiresKey))) {//缓存中不存在凭证有效期或失效{
            String requestUrl = QyWxApiUrls.ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", appSecret);
            JSONObject jsonObject = QyWxHttpUtils.sendGet(requestUrl);
            String errCode = jsonObject.getString("errcode");
            if (errCode.equals("0")) {
                token = jsonObject.getString("access_token");
                CacheUtils.put(wxTokenKey,token);//获取最新凭证
                CacheUtils.put(wxTokenExpiresKey,new Date(System.currentTimeMillis() + 60*60*1000));//设置凭证有效期为当前时间+1小时
            }else{
                String errMsg = jsonObject.getString("errmsg");
                logger.error("【企业微信】", "获取access_token失败，errCode：{}，errMsg：{}", new Object[]{errCode,errMsg});
            }
        }else {
            token = CacheUtils.get(wxTokenKey).toString();
        }
        return  token;
    }

    /**
     * 更新微信token，每次都取最新放入红缓存中
     * @param appId
     * @param appSecret
     * @param cacheKey
     * @return
     */
    public static String updateToken(String appId , String appSecret, String cacheKey) {
        String token = "";
        String wxTokenExpiresKey = "WxTokenExpires_" +cacheKey;
        String wxTokenKey = "WxToken_"+cacheKey;
        String requestUrl = QyWxApiUrls.ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", appSecret);
        JSONObject jsonObject = QyWxHttpUtils.sendGet(requestUrl);
        String errCode = jsonObject.getString("errcode");
        if (errCode.equals("0")) {
            token = jsonObject.getString("access_token");
            CacheUtils.put(wxTokenKey,token);//获取最新凭证
            CacheUtils.put(wxTokenExpiresKey,new Date(System.currentTimeMillis() + 60*60*1000));//设置凭证有效期为当前时间+1小时
        }else{
            String errMsg = jsonObject.getString("errmsg");
            logger.error("【企业微信】", "更新access_token失败，errCode：{}，errMsg：{}", new Object[]{errCode,errMsg});
        }
        return  token;
    }


    /** 获到企业微信jsapi_ticket
     * @param token
     * @return
     */
    public static String getTicket(String token) {
        String ticket = "";
        if(CacheUtils.get("WxTicketExpires") == null || CacheUtils.get("WxTicketExpires").equals("") || new Date().after((Date) CacheUtils.get("WxTicketExpires"))) {//缓存中不存在凭证有效期或失效{
            // 调用接口获取替换ACCESS_TOKEN
            String requestUrl = QyWxApiUrls.JSAPI_TICKET_URL.replace("ACCESS_TOKEN", token);
            JSONObject jsonObject = QyWxHttpUtils.sendGet(requestUrl);
            String errCode = jsonObject.getString("errcode");
            if(errCode.equals("0")){
                ticket = jsonObject.getString("ticket");
                CacheUtils.put("WxTicket",ticket);//获取最新凭证
                CacheUtils.put("WxTicketExpires",new Date(System.currentTimeMillis() + 60*60*1000));//设置凭证有效期为当前时间+1小时
            }else{
                String errMsg = jsonObject.getString("errmsg");
                logger.error("【企业微信】", "获取ticket失败，errCode：{}，errMsg：{}", new Object[]{errCode,errMsg});
            }
        }else {
            ticket = CacheUtils.get("WxTicket").toString();
        }
        return  ticket;
    }

    /**
     * 更新企业微信jsapi_ticket
     * @param token
     * @return
     */
    public static String updateTicket(String token) {
        // 调用接口获取替换ACCESS_TOKEN
        String ticket = "";
        String requestUrl = QyWxApiUrls.JSAPI_TICKET_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendGet(requestUrl);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            ticket = jsonObject.getString("ticket");
            CacheUtils.put("WxTicket",ticket);//获取最新凭证
            CacheUtils.put("WxTicketExpires",new Date(System.currentTimeMillis() + 60*60*1000));//设置凭证有效期为当前时间+1小时
        }else{
            String errMsg = jsonObject.getString("errmsg");
            logger.error("【企业微信】", "更新ticket失败，errCode：{}，errMsg：{}", new Object[]{errCode,errMsg});
        }
        return  ticket;
    }

    /** 获取应用的jsapi_ticket
     * @param token
     * @return
     */
    public static String getTicket_AgentConfig(String token) {
        String ticket = "";
        if(CacheUtils.get("WxTicketExpires_AgentConfig") == null || CacheUtils.get("WxTicketExpires_AgentConfig").equals("") || new Date().after((Date) CacheUtils.get("WxTicketExpires_AgentConfig"))) {//缓存中不存在凭证有效期或失效{
            // 调用接口获取替换ACCESS_TOKEN
            String requestUrl = QyWxApiUrls.JSAPI_TICKET_URL_AGENTCONFIG.replace("ACCESS_TOKEN", token);
            JSONObject jsonObject = QyWxHttpUtils.sendGet(requestUrl);
            String errCode = jsonObject.getString("errcode");
            if(errCode.equals("0")){
                ticket = jsonObject.getString("ticket");
                CacheUtils.put("WxTicket_AgentConfig",ticket);//获取最新凭证
                CacheUtils.put("WxTicketExpires_AgentConfig",new Date(System.currentTimeMillis() + 60*60*1000));//设置凭证有效期为当前时间+1小时
            }else{
                String errMsg = jsonObject.getString("errmsg");
                logger.error("【企业微信】", "获取ticket_agentConfig失败，errCode：{}，errMsg：{}", new Object[]{errCode,errMsg});
            }
        }else {
            ticket = CacheUtils.get("WxTicket_AgentConfig").toString();
        }
        return  ticket;
    }

    /**
     * 发送文本形式消息
     * @param userList 企业微信用户ID列表
     * @param deptList 企业微信部门ID列表，
     * @param tagList 企业微信标签ID列表
     * @param content 内容
     * @return
     */
    public static QyWxResponse sendTextMsg(List<String> userList, List<String> deptList, List<String> tagList, String content){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if ((userList == null ||  userList.size() == 0) && (deptList == null || deptList.size() == 0) && ( tagList == null || tagList.size() == 0)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】接收消息的成员列表[userList、deptList、tagList]三种类型成员不能同时为空，必须要有一种类型有值!");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(content)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】发送消息[content]内容参数不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("agentid",AGENTID);//企业应用的id，整型
        params.put("safe",0);//表示是否是保密消息，0表示可对外分享，1表示不能分享且内容显示水印，默认为0
        params.put("enable_id_trans",0);//表示是否开启id转译，0表示否，1表示是，默认0。仅第三方应用需要用到，企业自建应用可以忽略。
        params.put("enable_duplicate_check",0);//表示是否开启重复消息检查，0表示否，1表示是，默认0
        params.put("duplicate_check_interval",1800);//表示是否重复消息检查的时间间隔，默认1800s，最大不超过4小时
        params.put("msgtype","text");//消息类型，文本消息
        if (userList != null && userList.size() > 0){//用户
            params.put("touser", StringUtils.join(userList,"|"));
        }
        if (deptList != null && deptList.size() > 0){//部门
            params.put("toparty", StringUtils.join(deptList,"|"));
        }
        if (tagList != null && tagList.size() > 0){//标签
            params.put("totag", StringUtils.join(tagList,"|"));
        }
        Map<String, Object> sendContent = new HashMap<String, Object>();
        sendContent.put("content", content);
        params.put("text", sendContent);
        String postStr = JSONObject.toJSONString(params);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.MESSAGE_SEND_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】文本消息发送成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】文本消息发送失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 发送卡片形式消息
     * @param userList 企业微信用户ID列表
     * @param deptList 企业微信部门ID列表
     * @param tagList 企业微信标签ID列表
     * @param title 标题，不超过128个字节
     * @param content 描述，不超过512个字节
     * @param url 点击后跳转的链接。最长2048字节
     * @param btnTxt 按钮文字。 默认为“详情”， 不超过4个文字
     * @return
     */
    public static QyWxResponse sendActionCardMsg(List<String> userList, List<String> deptList, List<String> tagList, String title, String content, String url,  String btnTxt){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if ((userList == null ||  userList.size() == 0) && (deptList == null || deptList.size() == 0) && ( tagList == null || tagList.size() == 0)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】接收消息的成员列表[userList、deptList、tagList]三种类型成员不能同时为空，必须要有一种类型有值!");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(title)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】发送消息[title]内容参数不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(content)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】发送消息[content]内容参数不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(url)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】发送消息[url]内容参数不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("agentid",AGENTID);//企业应用的id，整型
        params.put("enable_id_trans",0);//表示是否开启id转译，0表示否，1表示是，默认0。仅第三方应用需要用到，企业自建应用可以忽略。
        params.put("enable_duplicate_check",0);//表示是否开启重复消息检查，0表示否，1表示是，默认0
        params.put("duplicate_check_interval",1800);//表示是否重复消息检查的时间间隔，默认1800s，最大不超过4小时
        params.put("msgtype","textcard");//消息类型，文本卡片消息
        if (userList != null && userList.size() > 0){//用户
            params.put("touser", StringUtils.join(userList,"|"));
        }
        if (deptList != null && deptList.size() > 0){//部门
            params.put("toparty", StringUtils.join(deptList,"|"));
        }
        if (tagList != null && tagList.size() > 0){//标签
            params.put("totag", StringUtils.join(tagList,"|"));
        }
        Map<String, Object> sendContent = new HashMap<String, Object>();
        sendContent.put("title", title);
        sendContent.put("description", content);
        sendContent.put("url", url);
        if (!StringUtils.isEmpty(btnTxt)){
            sendContent.put("btntxt", btnTxt);
        }
        params.put("textcard", sendContent);
        String postStr = JSONObject.toJSONString(params);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.MESSAGE_SEND_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】卡片消息发送成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】卡片消息发送失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 发送markdown形式消息
     * @param userList 企业微信用户ID列表
     * @param deptList 企业微信部门ID列表，
     * @param tagList 企业微信标签ID列表
     * @param content 内容(markdown格式的正文内容)
     * @return
     */
    public static QyWxResponse sendMarkDownMsg(List<String> userList, List<String> deptList, List<String> tagList, String content){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if ((userList == null ||  userList.size() == 0) && (deptList == null || deptList.size() == 0) && ( tagList == null || tagList.size() == 0)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】接收消息的成员列表[userList、deptList、tagList]三种类型成员不能同时为空，必须要有一种类型有值!");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(content)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】发送消息[content]内容参数不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("agentid",AGENTID);//企业应用的id，整型
        params.put("enable_duplicate_check",0);//表示是否开启重复消息检查，0表示否，1表示是，默认0
        params.put("duplicate_check_interval",1800);//表示是否重复消息检查的时间间隔，默认1800s，最大不超过4小时
        params.put("msgtype","markdown");//消息类型，文本消息
        if (userList != null && userList.size() > 0){//用户
            params.put("touser", StringUtils.join(userList,"|"));
        }
        if (deptList != null && deptList.size() > 0){//部门
            params.put("toparty", StringUtils.join(deptList,"|"));
        }
        if (tagList != null && tagList.size() > 0){//标签
            params.put("totag", StringUtils.join(tagList,"|"));
        }
        Map<String, Object> sendContent = new HashMap<String, Object>();
        sendContent.put("content", content);
        params.put("markdown", sendContent);
        String postStr = JSONObject.toJSONString(params);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.MESSAGE_SEND_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】markdown消息发送成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】markdown消息发送失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 创建日历
     * @param model
     * @return 有返回日历ID，放在AjaxResult的data参数中
     */
    public static QyWxResponse calendarCreate(CalendarEntity model){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (model == null){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】参数[model]对象不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getOrganizer())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日历组织者Id不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getSummary())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日历标题不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getColor())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日历显示的颜色不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> calendarParams = new HashMap<String, Object>();
        calendarParams.put("organizer",model.getOrganizer());
        calendarParams.put("readonly",model.getReadonly());
        calendarParams.put("set_as_default",model.getSetDefault());
        calendarParams.put("summary",model.getSummary());
        calendarParams.put("color",model.getColor());
        calendarParams.put("description",model.getDescription());
        List<Map<String, Object>> userList = new ArrayList<>();
        Map<String, Object> userMap = null;
        if (model.getUserIds() != null && model.getUserIds().size() > 0){
            for (String item: model.getUserIds()) {
                userMap = new HashMap<>();
                userMap.put("userid", item);
                userList.add(userMap);
            }
            calendarParams.put("shares",userList);
        }
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("calendar", calendarParams);
        sendParams.put("agentid", APPID);
        String postStr = JSONObject.toJSONString(sendParams);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.CALENDAR_CREATE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            String calendarId = jsonObject.getString("cal_id");
            qyWxResponse.setErrCode(0);
            qyWxResponse.setData(calendarId);
            qyWxResponse.setErrMsg("【企业微信】日历创建成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】日历创建失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 更新日历
     * @param model
     * @return
     */
    public static QyWxResponse calendarUpdate(CalendarEntity model){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (model == null){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】参数[model]对象不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getCalendarId())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日历Id不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getSummary())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日历标题不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getColor())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日历显示的颜色不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> calendarParams = new HashMap<String, Object>();
        calendarParams.put("cal_id",model.getCalendarId());
        calendarParams.put("readonly",model.getReadonly());
        calendarParams.put("summary",model.getSummary());
        calendarParams.put("color",model.getColor());
        calendarParams.put("description",model.getDescription());
        List<Map<String, Object>> userList = new ArrayList<>();
        Map<String, Object> userMap = null;
        if (model.getUserIds() != null && model.getUserIds().size() > 0){
            for (String item: model.getUserIds()) {
                userMap = new HashMap<>();
                userMap.put("userid", item);
                userList.add(userMap);
            }
            calendarParams.put("shares",userList);
        }
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("calendar", calendarParams);
        String postStr = JSONObject.toJSONString(sendParams);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.CALENDAR_UPDATE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】日历更新成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】日历更新失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 删除日历
     * @param calendarId 日历ID
     * @return
     */
    public static QyWxResponse calendarDelete(String calendarId){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (StringUtils.isEmpty(calendarId)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】参数[calendarId]不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("cal_id", calendarId);
        String postStr = JSONObject.toJSONString(sendParams);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.CALENDAR_DELETE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】日历删除成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】日历删除失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 企业微信日程创建
     * @param model
     * @return
     */
    public static QyWxResponse scheduleCreate(ScheduleEntity model){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (model == null){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】参数[model]对象不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getOrganizer())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程组织者Id不能为空！");
            return qyWxResponse;
        }
        if (model.getStartTime() == 0L){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程开始时间不能为零！");
            return qyWxResponse;
        }
        if (model.getEndTime() == 0L){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程开始时间不能为零！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getSummary())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程标题不能为空！");
            return qyWxResponse;
        }
        if (model.getCustomRepeat()== 1 && ((model.getRepeatDayOfWeek() == null || model.getRepeatDayOfWeek().size() == 0) && (model.getRepeatDayOfMonth() == null || model.getRepeatDayOfMonth().size() == 0))){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程当[customRepeat]设置为1时，[repeatDayOfWeek、repeatDayOfMonth]参数必须有一个设置值！");
            return qyWxResponse;
        }
        Map<String, Object> scheduleParams = new HashMap<String, Object>();
        scheduleParams.put("organizer",model.getOrganizer());
        scheduleParams.put("start_time",model.getStartTime());
        scheduleParams.put("end_time",model.getEndTime());
        scheduleParams.put("summary",model.getSummary());
        if (!StringUtils.isEmpty(model.getDescription())){
            scheduleParams.put("description",model.getDescription());
        }
        if (!StringUtils.isEmpty(model.getLocation())){
            scheduleParams.put("location",model.getLocation());
        }
        if (!StringUtils.isEmpty(model.getCalendarId())){
            scheduleParams.put("cal_id",model.getCalendarId());
        }
        List<Map<String, Object>> userList = new ArrayList<>();
        Map<String, Object> userMap = null;
        if (model.getUserIds() != null && model.getUserIds().size() > 0){
            for (String item: model.getUserIds()) {
                userMap = new HashMap<>();
                userMap.put("userid", item);
                userList.add(userMap);
            }
            scheduleParams.put("attendees",userList);
        }
        Map<String, Object> reminderMap = null;
        if (model.getRemind() == 1 || model.getRepeat() == 1) {
            reminderMap = new HashMap<>();
            reminderMap.put("is_remind", model.getRemind());
            reminderMap.put("remind_before_event_secs", model.getRemindSecond());
            reminderMap.put("is_repeat", model.getRepeat());
            reminderMap.put("timezone", model.getTimeZone());
            reminderMap.put("is_custom_repeat", model.getCustomRepeat());
            if (model.getRepeat() == 1){
                reminderMap.put("repeat_type", model.getRepeatType());
                reminderMap.put("repeat_until", model.getRepeatUntil());
                reminderMap.put("repeat_interval", model.getRepeatInterval());
            }
            if (model.getCustomRepeat()== 1 && (model.getRepeatDayOfWeek() != null && model.getRepeatDayOfWeek().size() > 0)){
                reminderMap.put("repeat_day_of_week", model.getRepeatDayOfWeek());
            }
            if (model.getCustomRepeat()== 1 && (model.getRepeatDayOfMonth() != null && model.getRepeatDayOfMonth().size() > 0)) {
                reminderMap.put("repeat_day_of_month", model.getRepeatDayOfMonth());
            }
            scheduleParams.put("reminders",reminderMap);
        }
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("schedule", scheduleParams);
        sendParams.put("agentid", APPID);
        String postStr = JSONObject.toJSONString(sendParams, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.SCHEDULE_CREATE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            String scheduleId = jsonObject.getString("schedule_id");
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】日程创建成功！");
            qyWxResponse.setData(scheduleId);
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】日程创建失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 企业微信日程更新
     * @param model
     * @return
     */
    public static QyWxResponse scheduleUpdate(ScheduleEntity model){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (model == null){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】参数[model]对象不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getScheduleId())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程ID不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getOrganizer())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程组织者Id不能为空！");
            return qyWxResponse;
        }
        if (model.getStartTime() == 0L){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程开始时间不能为零！");
            return qyWxResponse;
        }
        if (model.getEndTime() == 0L){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程开始时间不能为零！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getSummary())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程标题不能为空！");
            return qyWxResponse;
        }
        if (model.getCustomRepeat()== 1 && ((model.getRepeatDayOfWeek() == null || model.getRepeatDayOfWeek().size() == 0) && (model.getRepeatDayOfMonth() == null || model.getRepeatDayOfMonth().size() == 0))){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】日程当[customRepeat]设置为1时，[repeatDayOfWeek、repeatDayOfMonth]参数必须有一个设置值！");
            return qyWxResponse;
        }
        Map<String, Object> scheduleParams = new HashMap<String, Object>();
        scheduleParams.put("schedule_id",model.getScheduleId());
        scheduleParams.put("organizer",model.getOrganizer());
        scheduleParams.put("start_time",model.getStartTime());
        scheduleParams.put("end_time",model.getEndTime());
        scheduleParams.put("summary",model.getSummary());
        scheduleParams.put("skip_attendees",model.getSkipAttendees());
        if (!StringUtils.isEmpty(model.getDescription())){
            scheduleParams.put("description",model.getDescription());
        }
        if (!StringUtils.isEmpty(model.getLocation())){
            scheduleParams.put("location",model.getLocation());
        }
        List<Map<String, Object>> userList = new ArrayList<>();
        Map<String, Object> userMap = null;
        if (model.getUserIds() != null && model.getUserIds().size() > 0){
            for (String item: model.getUserIds()) {
                userMap = new HashMap<>();
                userMap.put("userid", item);
                userList.add(userMap);
            }
            scheduleParams.put("attendees",userList);
        }
        Map<String, Object> reminderMap = null;
        if (model.getRemind() == 1 || model.getRepeat() == 1) {
            reminderMap = new HashMap<>();
            reminderMap.put("is_remind", model.getRemind());
            reminderMap.put("remind_before_event_secs", model.getRemindSecond());
            reminderMap.put("is_repeat", model.getRepeat());
            reminderMap.put("timezone", model.getTimeZone());
            reminderMap.put("is_custom_repeat", model.getCustomRepeat());
            if (model.getRepeat() == 1){
                reminderMap.put("repeat_type", model.getRepeatType());
                reminderMap.put("repeat_until", model.getRepeatUntil());
                reminderMap.put("repeat_interval", model.getRepeatInterval());
            }
            if (model.getCustomRepeat()== 1 && (model.getRepeatDayOfWeek() != null && model.getRepeatDayOfWeek().size() > 0)){
                reminderMap.put("repeat_day_of_week", model.getRepeatDayOfWeek());
            }
            if (model.getCustomRepeat()== 1 && (model.getRepeatDayOfMonth() != null && model.getRepeatDayOfMonth().size() > 0)) {
                reminderMap.put("repeat_day_of_month", model.getRepeatDayOfMonth());
            }
        }
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("schedule", scheduleParams);
        String postStr = JSONObject.toJSONString(sendParams, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.SCHEDULE_UPDATE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            String scheduleId = jsonObject.getString("schedule_id");
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】日程更新成功！");
            qyWxResponse.setData(scheduleId);
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】日程更新失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 企业微信日程删除（取消）
     * @param scheduleId
     * @return
     */
    public static QyWxResponse scheduleDelete(String scheduleId){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (StringUtils.isEmpty(scheduleId)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("参数[scheduleId]不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("schedule_id", scheduleId);
        String postStr = JSONObject.toJSONString(sendParams);
        String token = getToken(APPID,H5SECERT, H5CACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.SCHEDULE_DELETE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】日程删除成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】日程删除失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 获取企业微信打卡记录数据
     * @param dataType
     * @param startTime
     * @param endTime
     * @param userList
     * @return
     */
    public static QyWxResponse getCheckinData(int dataType, long startTime, long endTime, List<String> userList){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (dataType == 0 || !"1,2,3,".contains(String.valueOf(dataType+","))){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】打卡类型参数[dataType]传值范围只能为[1,2,3]三种！");
            return qyWxResponse;
        }
        if (startTime == 0L){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】打卡开始时间参数[startTime]不能为零！");
            return qyWxResponse;
        }
        if (endTime == 0L){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】打卡结束时间参数[endTime]不能为零！");
            return qyWxResponse;
        }
        if (userList == null || userList.size() == 0){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】打卡用户列表参数[userList]不能为零！");
            return qyWxResponse;
        }
        Map<String, Object> sendParams = new HashMap<String, Object>();
        sendParams.put("opencheckindatatype", dataType);
        sendParams.put("starttime", startTime);
        sendParams.put("endtime", endTime);
        sendParams.put("useridlist", userList);
        String postStr = JSONObject.toJSONString(sendParams);
        String token = getToken(APPID,DKSECERT, DKCACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.CHECKIN_GET_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】打卡数据获取成功！");
            Object checkData = jsonObject.get("checkindata");
            qyWxResponse.setData(checkData);
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】打卡数据获取失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 创建企业微信用户
     * @param model
     * @return
     */
    public static QyWxResponse userCreate(UserEntity model){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (model == null){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】参数[model]对象不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getUserId())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】userId参数不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getUserName())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】userName参数不能为空！");
            return qyWxResponse;
        }
        if (model.getDepartment() == null || model.getDepartment().size() == 0){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】department参数不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getMobile())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】mobile参数不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> userParams = new HashMap<String, Object>();
        userParams.put("userid",model.getUserId());
        userParams.put("name",model.getUserName());
        if (!StringUtils.isEmpty(model.getAlias())) {
            userParams.put("alias", model.getMobile());
        }
        if (!StringUtils.isEmpty(model.getMobile())) {
            userParams.put("mobile", model.getMobile());
        }
        if (!StringUtils.isEmpty(model.getTelephone())) {
            userParams.put("telephone", model.getTelephone());
        }
        if (model.getDepartment() !=null && model.getDepartment().size() >0) {
            userParams.put("department", model.getDepartment());
        }
        if (!StringUtils.isEmpty(model.getPosition())) {
            userParams.put("position", model.getPosition());
        }
        if (!StringUtils.isEmpty(model.getGender())) {
            userParams.put("gender", model.getGender());
        }
        if (!StringUtils.isEmpty(model.getEmail())) {
            userParams.put("email", model.getEmail());
        }
        if (!StringUtils.isEmpty(model.getBizMail())) {
            userParams.put("biz_mail", model.getBizMail());
        }
        if (!StringUtils.isEmpty(model.getDirectLeader())) {
            userParams.put("direct_leader", model.getDirectLeader());
        }
        userParams.put("enable", model.getEnable());
        if (!StringUtils.isEmpty(model.getAddress())) {
            userParams.put("address", model.getAddress());
        }
        String postStr = JSONObject.toJSONString(userParams, SerializerFeature.WriteNullStringAsEmpty);
        String token = getToken(APPID,TXLSECERT, TXLCACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.USER_CREATE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】用户信息同步创建成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】打用户信息同步创建失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 更新企业微信用户
     * @param model
     * @return
     */
    public static QyWxResponse userUpdate(UserEntity model){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (model == null){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】参数[model]对象不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getUserId())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】userId参数不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getUserName())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】userName参数不能为空！");
            return qyWxResponse;
        }
        if (StringUtils.isEmpty(model.getMobile())){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】mobile参数不能为空！");
            return qyWxResponse;
        }
        Map<String, Object> userParams = new HashMap<String, Object>();
        userParams.put("userid",model.getUserId());
        userParams.put("name",model.getUserName());
        if (!StringUtils.isEmpty(model.getAlias())) {
            userParams.put("alias", model.getMobile());
        }
        if (!StringUtils.isEmpty(model.getMobile())) {
            userParams.put("mobile", model.getMobile());
        }
        if (!StringUtils.isEmpty(model.getTelephone())) {
            userParams.put("telephone", model.getTelephone());
        }
        if (model.getDepartment() !=null && model.getDepartment().size() >0) {
            userParams.put("department", model.getDepartment());
        }
        if (!StringUtils.isEmpty(model.getPosition())) {
            userParams.put("position", model.getPosition());
        }
        if (!StringUtils.isEmpty(model.getGender())) {
            userParams.put("gender", model.getGender());
        }
        if (!StringUtils.isEmpty(model.getEmail())) {
            userParams.put("email", model.getEmail());
        }
        if (!StringUtils.isEmpty(model.getBizMail())) {
            userParams.put("biz_mail", model.getBizMail());
        }
        if (!StringUtils.isEmpty(model.getDirectLeader())) {
            userParams.put("direct_leader", model.getDirectLeader());
        }
        userParams.put("enable", model.getEnable());
        if (!StringUtils.isEmpty(model.getAddress())) {
            userParams.put("address", model.getAddress());
        }
        String postStr = JSONObject.toJSONString(userParams, SerializerFeature.WriteNullStringAsEmpty);
        String token = getToken(APPID,TXLSECERT, TXLCACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.USER_UPDATE_URL.replace("ACCESS_TOKEN", token);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, postStr);
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】用户信息同步更新成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】打用户信息同步更新失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }

    /**
     * 删除企业微信用户
     * @param userId
     * @return
     */
    public static QyWxResponse userDelete(String userId){
        QyWxResponse qyWxResponse = new QyWxResponse();
        if (StringUtils.isEmpty(userId)){
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg("【企业微信】userId参数不能为空！");
            return qyWxResponse;
        }
        String token = getToken(APPID,TXLSECERT, TXLCACHEKEY);
        //发起请求
        String requestUrl = QyWxApiUrls.USER_DELETE_URL.replace("ACCESS_TOKEN", token).replace("USERID", userId);
        JSONObject jsonObject = QyWxHttpUtils.sendPost(requestUrl, "");
        String errCode = jsonObject.getString("errcode");
        if(errCode.equals("0")){
            qyWxResponse.setErrCode(0);
            qyWxResponse.setErrMsg("【企业微信】用户信息同步删除成功！");
        }else {
            String errMsg = jsonObject.getString("errmsg");
            qyWxResponse.setErrCode(500);
            qyWxResponse.setErrMsg(String.format("【企业微信】打用户信息同步删除失败，具体错误为：errCode：%s，errMsg：%s", errCode,errMsg));
        }
        return qyWxResponse;
    }
}
